package cn.ctodb.wxmp.web.rest;

import com.codahale.metrics.annotation.Timed;
import cn.ctodb.wxmp.service.TokenService;
import cn.ctodb.wxmp.web.rest.util.HeaderUtil;
import cn.ctodb.wxmp.web.rest.util.PaginationUtil;
import cn.ctodb.wxmp.service.dto.TokenDTO;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing Token.
 */
@RestController
@RequestMapping("/api")
public class TokenResource {

    private final Logger log = LoggerFactory.getLogger(TokenResource.class);
        
    @Inject
    private TokenService tokenService;

    /**
     * POST  /tokens : Create a new token.
     *
     * @param tokenDTO the tokenDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tokenDTO, or with status 400 (Bad Request) if the token has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tokens")
    @Timed
    public ResponseEntity<TokenDTO> createToken(@RequestBody TokenDTO tokenDTO) throws URISyntaxException {
        log.debug("REST request to save Token : {}", tokenDTO);
        if (tokenDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("token", "idexists", "A new token cannot already have an ID")).body(null);
        }
        TokenDTO result = tokenService.save(tokenDTO);
        return ResponseEntity.created(new URI("/api/tokens/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("token", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /tokens : Updates an existing token.
     *
     * @param tokenDTO the tokenDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tokenDTO,
     * or with status 400 (Bad Request) if the tokenDTO is not valid,
     * or with status 500 (Internal Server Error) if the tokenDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tokens")
    @Timed
    public ResponseEntity<TokenDTO> updateToken(@RequestBody TokenDTO tokenDTO) throws URISyntaxException {
        log.debug("REST request to update Token : {}", tokenDTO);
        if (tokenDTO.getId() == null) {
            return createToken(tokenDTO);
        }
        TokenDTO result = tokenService.save(tokenDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("token", tokenDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /tokens : get all the tokens.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of tokens in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/tokens")
    @Timed
    public ResponseEntity<List<TokenDTO>> getAllTokens(@ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Tokens");
        Page<TokenDTO> page = tokenService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tokens");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /tokens/:id : get the "id" token.
     *
     * @param id the id of the tokenDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tokenDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tokens/{id}")
    @Timed
    public ResponseEntity<TokenDTO> getToken(@PathVariable Long id) {
        log.debug("REST request to get Token : {}", id);
        TokenDTO tokenDTO = tokenService.findOne(id);
        return Optional.ofNullable(tokenDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /tokens/:id : delete the "id" token.
     *
     * @param id the id of the tokenDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tokens/{id}")
    @Timed
    public ResponseEntity<Void> deleteToken(@PathVariable Long id) {
        log.debug("REST request to delete Token : {}", id);
        tokenService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("token", id.toString())).build();
    }

    /**
     * SEARCH  /_search/tokens?query=:query : search for the token corresponding
     * to the query.
     *
     * @param query the query of the token search 
     * @param pageable the pagination information
     * @return the result of the search
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/_search/tokens")
    @Timed
    public ResponseEntity<List<TokenDTO>> searchTokens(@RequestParam String query, @ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to search for a page of Tokens for query {}", query);
        Page<TokenDTO> page = tokenService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tokens");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }


}
